package com.wlyuan.open.scanner.domain.vehicle;

import com.wlyuan.open.scanner.dao.entity.CarDO;
import com.wlyuan.open.scanner.utils.JsonUtils;
import com.wlyuan.open.scanner.utils.mappings.BaseMapping;
import com.wlyuan.open.scanner.utils.mappings.MappingInvalid;
import org.apache.commons.lang3.StringUtils;
import org.mapstruct.*;
import org.mapstruct.factory.Mappers;

import java.util.List;

/**
 * @author lijing
 * @description
 */
public class VehicleConvert {

    private static final Convert CONVERT = Mappers.getMapper(Convert.class);

    @Mapper(uses = MappingInvalid.class)
    public interface Convert {

        @Mappings({
                @Mapping(target = "id", source = "carId"),
                @Mapping(target = "brand", source = "carBrand"),
                @Mapping(target = "buyDate", source = "carPurchasetime"),
                @Mapping(target = "imageUrl", source = "carPhoto"),
                @Mapping(target = "insuranceEndDate", source = "carInsurance"),
                @Mapping(target = "length", source = "carLength"),
                @Mapping(target = "loadWeight", source = "carWeight"),
                @Mapping(target = "plateNo", source = "carSn"),
                @Mapping(target = "seats", source = "carSeats"),
                @Mapping(target = "type", source = "carType"),
                @Mapping(target = "volume", source = "carVolume"),

                @Mapping(target = "tenantId", source = "carCompanyid"),
                @Mapping(target = "sourceKey", source = "carId"),
                @Mapping(target = "createTime", source = "carInserttime"),
                @Mapping(target = "updateTime", source = "carUpdatetime"),
                @Mapping(target = "createBy", source = "carCreator"),
                @Mapping(target = "updateBy", source = "carUpdater"),
        })
        @BaseMapping
        Vehicle convert(CarDO carDO);

        /**
         * after
         *
         * @param target
         * @param source
         */
        @AfterMapping
        default void after(@MappingTarget Vehicle target, CarDO source) {
            target.setRaw(JsonUtils.withNullJson(source));
            if (StringUtils.isBlank(target.getBrand())) {
                target.setBrand("其它");
            }
            if (target.getBuyDate() == null && target.getCreateTime() != null) {
                target.setBuyDate(target.getCreateTime().toLocalDate());
            }
            if (target.getInsuranceEndDate() == null && target.getCreateTime() != null) {
                target.setInsuranceEndDate(target.getCreateTime().toLocalDate());
            }
        }

        List<Vehicle> convert(List<CarDO> list);

    }

    public static List<Vehicle> convert(List<CarDO> creation) {
        return CONVERT.convert(creation);
    }

    public static Vehicle convert(CarDO creation) {
        return CONVERT.convert(creation);
    }
}
